package com.pink.task;

import com.pink.component.RedisComponent;
import com.pink.entity.config.AppConfig;
import com.pink.entity.config.Constants;
import com.pink.entity.query.EmailQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class MailQueueTask {
    private ExecutorService executorService = Executors.newFixedThreadPool(Constants.LENGTH_1);

    @Resource
    JavaMailSender mailSender;

    @Resource
    AppConfig appConfig;

    @Resource
    private RedisComponent redisComponent;

    @PostConstruct
    public void sendMailQueues() {
        executorService.execute(()->{
            try {
                while (true) {
                    //消费队列中的邮件信息
                    EmailQuery query = redisComponent.getEmailQueue();
                    if(query == null){
                        Thread.sleep(15000); //每隔15秒检查一次队列
                        continue;
                    }
                    sendMailMessage(query);
                }
            }catch (Exception e) {
                log.error("邮件发送异常",e);
            }
        });
    }

    public void sendMailMessage(EmailQuery data) {
        String email = data.getEmail();
        Integer code = data.getCode();
        String type = data.getType();
        SimpleMailMessage message = switch (type){
            case "register" ->
                    createMessage("欢迎注册团星网",
                            "你的邮箱注册验证码为:"+code+",有效时间3分钟，为了保障你的安全，请勿告诉其他人验证码信息。"
                            ,email);
            case "reset" -> createMessage("你正在重置密码",
                    "你好，你正在进行重置密码操作，验证码："+code+",有效时间3分钟，如非本人操作，请忽略本信息。"
                    ,email);
            default -> null;
        };
        if(message == null) return;
        mailSender.send(message);
    }

    private SimpleMailMessage createMessage(String title,String content,String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);
        message.setText(content);
        message.setTo(email);
        message.setFrom(appConfig.getEmailUserName());
        return message;
    }
}
